﻿using Microsoft.AspNetCore.Mvc;
using TencentCloud.Eiam.V20210420.Models;
using ZenSystemService.Api.Common.Auth;
using ZenSystemService.Api.DTOs;
using ZenSystemService.Api.DTOs.Auth;
using ZenSystemService.Api.DTOs.FileResource;
using ZenSystemService.Api.Services;

namespace ZenSystemService.Api.Controllers
{
    [Route("api/resources")]
    [ApiController]
    public class ResourceController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        private readonly ILogger _logger;

        public ResourceController(IConfiguration configuration, ILogger<ResourceController> logger)
        {
            _configuration = configuration;
            _logger = logger;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <param name="directory">eg. Images, Images/Fingerprints</param>
        /// <returns></returns>
        [HttpPost("uploadImage")]
        public async Task<ActionResult> UploadImage([FromForm] IFormFile file, [FromForm] string directory)
        {
            var dir = directory.TrimStart('/', '\\');
            if (file == null || file.Length == 0)
            {
                return BadRequest("No file uploaded.");
            }
            if(string.IsNullOrEmpty(directory) || !IsValidPath(directory)) 
            {
                return BadRequest("Invalid directory provided.");
            }

            try
            {
                var rootPath = _configuration.GetValue<string>("ResourceServerRootPath");
                var targetDirectory = Path.Combine(rootPath, dir);
                if(!Directory.Exists(targetDirectory))
                {
                    Directory.CreateDirectory(targetDirectory);
                    _logger.LogInformation("Create directory successfully.");
                }
                var filePath = Path.Combine(targetDirectory, file.FileName);
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
                
                var fullUri = GetFileUri(directory, file.FileName);
                var result = new FileResourceCreateResultDTO
                {
                    FileUrl = fullUri
                };
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "");
                return StatusCode(500, new { Message = ex.ToString() });
            }
        }

        private string GetFileUri(string directory, string filename)
        {
            var protocal = "https";
            var host = _configuration.GetValue<string>("ResourceHost");
            var path = directory.TrimEnd('/') + "/";
            var baseUri = new Uri($"{protocal}://{host}");
            var fullUri = new Uri(baseUri, path + filename.TrimStart('/'));
            return fullUri.AbsoluteUri;
        }

        private bool IsValidPath(string path)
        {
            char[] invalidPathChars = Path.GetInvalidPathChars();
            foreach (char c in path)
            {
                if (invalidPathChars.Contains(c))
                {
                    return false;
                }
            }
            return true;
        }
    }
}